/* eslint-disable react/jsx-handler-names */
/**
 * 自定义地区组件
 * create by zxy 2019.12.17
 */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Row, Col } from 'antd';
import { FormItemLayout, SelectC } from '../../form';

class AddressC extends React.PureComponent {
  // 默认值
  static defaultProps = {
    provInit: undefined,
    cityInit: undefined,
    onChange: () => {},
    onRef: () => {}, // 本组件的引用
    rules: [], // 校验规则
    isMultiple: false, // 默认单选
    provinceDataTitle: '省份',
    cityDataTitle: '城市',
  };

  constructor(props) {
    super(props);
    this.state = {
      currentProv: undefined, // 当前选中的省ID
      currentCity: undefined, // 当前选中的市ID
      citys: [], // 当前选中的省下对应的市信息
    };
  }

  // 根据省份ID获取市下拉列表信息
  getCityInfo = (provId, props) => {
    const { isMultiple } = this.props;
    const { addressInfo } = props.addressM;
    let currentProv = [];
    let citysSource = [];
    if (provId && JSON.stringify(provId) !== '[]') {
      if (isMultiple) {
        // 多选模式将已选中的省份包含的城市添加进城市下拉选项
        if (provId && provId.length)
          provId.map((item) => {
            addressInfo.map((items) => {
              if (item == items.id) {
                citysSource = _.concat(citysSource, items.children);
              }
            });
          });
      } else {
        // 单选模式筛选出已选择的省份，将期内部城市添加进城市下拉
        currentProv = addressInfo.filter((item) => item.id == provId);
        citysSource = !currentProv || currentProv.length == 0 ? [] : currentProv[0].children;
      }
    } else {
      addressInfo.map((items) => {
        citysSource = _.concat(citysSource, items.children);
      });
    }
    const citys = [];
    citysSource.forEach((element) => {
      citys.push({
        value: element.id,
        title: element.name,
      });
    });
    return citys;
  };

  // 更改市信息（包含下拉列表和选中项）
  changeCityInfo = (citys, selectProv, selectCity, props) => {
    const { isMultiple } = this.props;
    // 改变“市”的下拉内容
    this.setState({
      citys,
      currentProv: selectProv,
      currentCity: selectCity,
    });
    // 设置city的值
    this.state.citySelect.setSelect(isMultiple ? (selectCity && selectCity instanceof Array ? selectCity : []) : selectCity);
    // 发送onChange事件
    props.onChange({ province: selectProv, city: selectCity });
  };

  componentDidMount() {
    // 父组件对本组件的引用
    this.props.onRef(this);
    const { isMultiple } = this.props;
    // model目录：@bcomp/models/addressM
    // 获取省市信息，信息存在addressM.province中
    this.props.dispatch({
      type: 'addressM/getLocation',
    });

    // 根据省份ID获取市下拉列表信息
    const citys = this.getCityInfo(this.props.provInit, this.props);
    // 更改市信息（包含下拉列表和选中项）
    this.changeCityInfo(citys, this.props.provInit, this.props.cityInit ? this.props.cityInit : undefined, this.props);
  }

  // 非初始化状态下更改下拉选项(供父组件调用)
  setAddress = ({ province, city }) => {
    // 设置省份
    this.state.provSelect.setSelect(province);

    // 根据省份ID获取市下拉列表信息
    const citys = this.getCityInfo(province, this.props);

    // 更改市信息（包含下拉列表和选中项）
    this.changeCityInfo(citys, province, city, this.props);
  };

  // “省份”切换变更事件
  provOnChange = (value) => {
    const { isMultiple, allowClear } = this.props;
    // 根据省份ID获取市下拉列表信息
    this.state.citySelect.setSelect(undefined);
    const citys = this.getCityInfo(value, this.props);

    // 更改市信息（包含下拉列表和选中项）
    if (isMultiple || (allowClear && !value)) {
      this.changeCityInfo(citys, value, undefined, this.props); // 多选模式下无默认值 || 或者可以清除时，清除省份时需要同时清除城市
    } else {
      this.changeCityInfo(citys, value, citys.length > 0 ? citys[0].value : undefined, this.props);
    }
  };

  // “市”切换变更事件
  cityOnChange = (value) => {
    // 发送onChange事件
    this.props.onChange({ province: this.state.currentProv, city: value });
  };

  componentDidUpdate(preProps) {
    const { addressM: addressMT, provInit: provInitT, cityInit: cityInitT, isMultiple } = preProps;
    const { addressM: addressMN, provInit: provInitN, cityInit: cityInitN } = this.props;
    const { addressInfo: addressInfoT } = addressMT;
    const { addressInfo: addressInfoN } = addressMN;
    if (addressInfoT.length !== addressInfoN.length || provInitT !== provInitN || cityInitT !== cityInitN) {
      // 根据省份ID获取市下拉列表信息
      const citys = this.getCityInfo(this.props.provInit, this.props);
      this.changeCityInfo(citys, this.props.provInit, this.props.cityInit ? this.props.cityInit : undefined, this.props);
    }
  }

  render() {
    const { provinceDataTitle, cityDataTitle, form, style, formItemLayout, loading, addressM, provinceDataIndex, cityDataIndex, rules, isMultiple, disabled } = this.props;
    const { province } = addressM;
    const { currentProv, currentCity } = this.state;
    return (
      <Row style={style}>
        <Col span={12}>
          <SelectC
            {...this.props}
            rules={rules[0]}
            title={provinceDataTitle}
            form={form}
            dataIndex={provinceDataIndex}
            onChange={this.provOnChange}
            placeholder='请选择省份'
            formItemLayout={formItemLayout ? formItemLayout : FormItemLayout}
            initialValue={isMultiple ? (currentProv && currentProv instanceof Array ? currentProv : []) : currentProv}
            filterOption={(input, option) => {
              return option.props.children.toLowerCase().indexOf(input.toLowerCase()) > -1;
            }}
            dataSource={province}
            loading={loading.effects['addressM/getLocation']}
            onRef={(ref) => (this.state.provSelect = ref)}
            isMultiple={isMultiple}
            disabled={disabled}
            positionBody={this.props.positionBody}
          />
        </Col>
        <Col span={12}>
          <SelectC
            {...this.props}
            form={form}
            rules={rules[1]}
            title={cityDataTitle}
            dataIndex={cityDataIndex}
            onChange={this.cityOnChange}
            placeholder='请选择城市'
            formItemLayout={formItemLayout ? formItemLayout : FormItemLayout}
            dataSource={this.state.citys}
            filterOption={(input, option) => {
              return option.props.children.toLowerCase().indexOf(input.toLowerCase()) > -1;
            }}
            initialValue={isMultiple ? (currentCity && currentCity instanceof Array ? currentCity : []) : currentCity}
            loading={false}
            // eslint-disable-next-line react/no-direct-mutation-state
            onRef={(ref) => (this.state.citySelect = ref)}
            isMultiple={isMultiple}
            disabled={disabled || !this.state.currentProv}
            positionBody={this.props.positionBody}
          />
        </Col>
      </Row>
    );
  }
}

// props默认值
AddressC.propsTypes = {
  form: PropTypes.object, // form对象
  style: PropTypes.object, // 样式
  provinceDataIndex: PropTypes.string, // “省”Form识别的Item ID
  cityDataIndex: PropTypes.string, // “市”Form识别的Item ID
  provInit: PropTypes.oneOfType([
    // “省”初始值
    PropTypes.string,
    PropTypes.number,
    PropTypes.array,
  ]),
  cityInit: PropTypes.oneOfType([
    // “市”初始值
    PropTypes.string,
    PropTypes.number,
    PropTypes.array,
  ]),
  onChange: PropTypes.func, // 选项变更事件(省和市下拉变更)
  formItemLayout: PropTypes.object, // layout布局设置
  onRef: PropTypes.func, // 本组件的引用（可用来父组件调用内部方法）
  rules: PropTypes.array, // 校验规则
  isMultiple: PropTypes.bool,
};

export default connect(({ addressM, loading }) => ({ addressM, loading }))(AddressC);
